import  requests
from threading import Thread
import time
from  multiprocessing import Process
## 定义CPU 秘籍的计算函数
def count(x,y):
    c=0
    while c<10000:
        c+=1
        x+=1
        y+=1

#使用多线程 并发执行CPU秘籍操作所需要的时间
def MultiThread_Cpu():
    counts = []
    t = time.time()
    for i in range(10):
        ts = Thread(target=count, args=(1, 1))
        #打印 多线程的名字
        print(ts.getName(),ts.is_alive())
        counts.append(ts)
        ts.start()
    for tt in counts:
        tt.join()
    e = counts.__len__()
    while True:
        for th in counts:
            if not th.is_alive():
             e -= 1
        if e <= 0:
            break
    print("MultiThread cpu",time.time() - t)


#多线程测试 网路请求 
def MultiThread_Http():
    counts = []
    t = time.time()
    for i in range(10):
        ts = Thread(target=http_request)
        #打印 多线程的名字
        print(ts.getName(),ts.is_alive())
        counts.append(ts)
        ts.start()
    for tt in counts:
        tt.join()
    e = counts.__len__()
    while True:
        for th in counts:
            if not th.is_alive():
             e -= 1
        if e <= 0:
            break
    print("MultiThread Http",time.time() - t)


#使用多进程 并发执行CPU秘籍操作所需要的时间
def Multiprocess_cpu():
    process = []
    t = time.time()
    for i in range(10):
        p = Process(target=count, args=(1, 1))
        # 打印 多进程的名字
        print(p.name)
        process.append(p)
        p.start()
    for pp in process:
        pp.join()

    e = process.__len__()
    while True:
        for th in process:
            if not  th.is_alive():
             e -= 1
        if e <= 0:
            break

    print("Multiprocess cpu", time.time() - t)


def http_request():
    url = "https://www.baidu.com/"
    # body=""
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36"
    }
    try:
       request= requests.get(url,headers=headers)
       html=request.text
       return {"context":html}
    except Exception as e:
        return  {"error":e}



# 多进程测试 网路请求
def Multiprocess_Http():
    process = []
    t = time.time()
    for i in range(10):
        p = Process(target=http_request)
        # 打印 多进程的名字
        print(p.name)
        process.append(p)
        p.start()
    for pp in process:
        pp.join()
    e = process.__len__()
    while True:
        for th in process:
         if not th.is_alive():
            e -= 1
        if e <= 0:
            break

    print("Multiprocess Http", time.time() - t)


# 主线程
if __name__ == '__main__':
    #print("-----------Cpu--------")
    # print(Multiprocess_cpu())

    #print(MultiThread_Cpu())

    print("--------------http--------")
    print(Multiprocess_Http())
    print(MultiThread_Http())